/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import { QuestionCircleOutlined } from '@ant-design/icons';
import { Drawer, message, Popover, Row, Typography } from 'antd';
import { ProFormInstance } from '@ant-design/pro-form';
import { ProFormCheckbox } from '@ant-design/pro-form';
import ProForm, { ProFormDateRangePicker, ProFormRadio, ProFormText } from '@ant-design/pro-form';
import type { ConnectState } from '@/models/connect';
import { useSelector } from 'umi';
import React, { useRef, useState, useEffect } from 'react';
import KbAddressSelect from './KbAddressSelect';
import { addRegionAdmin, areaManageDetail } from '@/services/Inn/ChargeCheck';
import AgencyArea from './AgencyArea';

const { Title, Text } = Typography;

interface AreamanageDrawerType {
  id?: string;
  update: () => void;
}

const AreamanageDrawer: React.FC<AreamanageDrawerType> = (props) => {
  const { children, update, id = '' } = props;
  const formRef = useRef<ProFormInstance>();
  const [visible, setVisible] = useState<boolean>(false);
  const [address, setAddress] = useState<any>([]);
  const [dataDetail, setDataDetail] = useState<Record<string, string>>({});

  const { winSize } = useSelector((state: ConnectState) => state.global);
  const isMobile = winSize === 'xs';

  const getDetail = async () => {
    const { code, data } = await areaManageDetail({ id });
    if (code == 0) {
      const {
        company_name,
        service_fee,
        start_date,
        end_date,
        concat_name,
        contact_phone,
        address: detailAddr,
        province,
        city,
        district,
        town,
        is_need_check,
        is_complate,
        complate_edit,
        show_individual,
        is_sitescan,
        ...rest
      } = data;
      formRef.current?.setFieldsValue({
        jmsName: company_name || '',
        date: [start_date, end_date],
        contact: concat_name || '',
        contactPhone: contact_phone,
        fee: service_fee,
        detailAddr,
        address: `${province}${city}${district}${town}`,
        is_complate: is_complate == '1',
        complate_edit: complate_edit == '1',
        is_need_check: is_need_check == '1',
        show_individual: show_individual == '1',
        is_sitescan: is_sitescan == '1',
        ...rest,
      });
      setDataDetail(data);
    }
  };

  useEffect(() => {
    if (id && visible) {
      getDetail();
    }
  }, [id, visible]);

  const formatCompanyAddress = (addressCity: string | string[]) => {
    const { province_code, city_code, district_code, town_code } = dataDetail;
    const isChange = typeof addressCity == 'string';
    const companyAddress = isChange
      ? {
          province: province_code,
          city: city_code,
          district: district_code,
          town: town_code,
        }
      : {
          province: address[0]?.code,
          city: address[1]?.code,
          district: address[1]?.code,
          town: address[3]?.code,
        };

    return companyAddress;
  };

  const onFinish = async (values: any) => {
    const {
      date = [],
      address: addressCity,
      is_need_check,
      is_complate,
      show_individual,
      complate_edit,
      is_sitescan,
      ...rest
    } = values;

    const params = {
      ...rest,
      dateStart: date[0],
      dateEnd: date[1],
      ...formatCompanyAddress(addressCity),
      is_need_check: is_need_check ? '1' : '0',
      is_complate: is_complate ? '1' : '0',
      complate_edit: complate_edit ? '1' : '0',
      show_individual: show_individual ? '1' : '0',
      is_sitescan: is_sitescan ? '1' : '0',
    };

    if (dataDetail.id) {
      params.id = dataDetail.id;
    }

    const { code, msg } = await addRegionAdmin(params);
    if (code == 0) {
      message.info('成功');
      setVisible(false);
      update();
    } else {
      message.error(msg);
    }
  };

  return (
    <>
      <div onClick={() => setVisible(true)}>{children}</div>
      <Drawer visible={visible} onClose={() => setVisible(false)} width={isMobile ? '' : 700}>
        <ProForm
          formRef={formRef}
          layout='horizontal'
          labelCol={{ span: 6 }}
          labelWrap
          onFinish={onFinish}
          colon={false}
          submitter={{
            searchConfig: {
              resetText: '重置',
              submitText: '保存',
            },
            resetButtonProps: {
              style: dataDetail.id
                ? {
                    // 隐藏重置按钮
                    display: 'none',
                  }
                : {},
            },
          }}
        >
          <ProFormText
            label='加盟商名称'
            name={'jmsName'}
            width={'sm'}
            placeholder='请输入加盟商名称'
            rules={[{ required: true, message: '请输入加盟商名称' }]}
          />
          <ProFormDateRangePicker
            name='date'
            label='加盟时间'
            required
            dataFormat='YYYY-MM-DD'
            rules={[{ required: true, message: '请输入加盟商时间' }]}
          />
          <ProFormText
            label='联系人'
            required
            width={'sm'}
            name='contact'
            placeholder='请输入联系人'
            rules={[{ required: true, message: '请输入联系人' }]}
          />
          <ProFormText
            label='注册手机号'
            required
            fieldProps={{
              suffix: (
                <Popover trigger={'hover'} content='注册后不可修改'>
                  <QuestionCircleOutlined />
                </Popover>
              ),
            }}
            width={'sm'}
            name='phone'
            placeholder='请输入注册手机号'
            rules={[{ required: true, message: '请输入注册手机号' }]}
          />
          <ProFormText
            label='联系手机号'
            required
            fieldProps={{
              suffix: (
                <Popover
                  trigger={'hover'}
                  content='用于代理区域内驿站联系，可修改，可与注册手机号相同'
                >
                  <QuestionCircleOutlined />
                </Popover>
              ),
            }}
            width={'sm'}
            name='contactPhone'
            placeholder='请输入联系手机号'
            rules={[{ required: true, message: '请输入联系手机号' }]}
          />
          <ProForm.Item
            label='加盟商地址'
            name={'address'}
            rules={[{ required: true, message: '请输入加盟商地址' }]}
          >
            <KbAddressSelect
              placeholder='请输入加盟商地址'
              onChange={(_, options) => setAddress(options)}
            />
          </ProForm.Item>
          <ProFormText
            name='detailAddr'
            label='详细地址'
            width={'sm'}
            placeholder='详细地址'
            rules={[{ required: true, message: '请输入详细地址' }]}
          />

          <ProForm.Item label='代理区域' name='agency_area'>
            <AgencyArea />
          </ProForm.Item>

          <ProFormRadio.Group
            label='发票类型'
            name='is_special'
            required
            initialValue='0'
            options={[
              {
                label: '特许加盟商',
                value: '1',
              },
              {
                label: '普通加盟商',
                value: '0',
              },
            ]}
          />
          <ProFormText
            label='服务费金额'
            required
            fieldProps={{
              suffix: '元',
            }}
            width={'sm'}
            name='fee'
            placeholder='服务费金额'
            rules={[{ required: true, message: '请输入服务费金额' }]}
          />
          <ProFormText
            label='快宝抽成服务费比例'
            required
            fieldProps={{
              suffix: '%',
            }}
            width={'sm'}
            name='service_share_ratio'
            placeholder='快宝抽成服务费比例'
            rules={[{ required: true, message: '请输入快宝抽成服务费比例' }]}
          />
          <ProFormCheckbox label=' ' name={'is_complate'}>
            兼容入库
          </ProFormCheckbox>
          <ProFormCheckbox label=' ' name='complate_edit'>
            允许加盟商编辑
          </ProFormCheckbox>
          <ProFormText
            label='兼容入库服务费'
            required
            fieldProps={{
              suffix: '元/单',
            }}
            width={'sm'}
            name='complate_fee'
            placeholder='兼容入库服务费'
            rules={[{ required: true, message: '请输入兼容入库服务费' }]}
          />
          <ProFormCheckbox label=' ' name={'is_need_check'}>
            区域内新注册驿站需要经过该加盟商审核通过才可开通出入库功能
          </ProFormCheckbox>
          <ProFormCheckbox label=' ' name={'show_individual'}>
            显示 区域内独立驿站
          </ProFormCheckbox>
          <ProFormCheckbox label=' ' name={'is_sitescan'}>
            场地扫描投件
          </ProFormCheckbox>
        </ProForm>

        <Row style={{ marginTop: 10 }}>
          <Title level={5}>备注：</Title>
          <Text>
            1、关于加盟商的账户说明： 如加盟商已经在http://city.kuaidihelp.com/
            里注册，请确保该加盟商的注册手机号码和这里的一致。
            如这里输入的手机号码未在http://city.kuaidihelp.com/
            里注册，会自动生成一个账户，请让加盟商使用登录时的“找回密码”功能，重置密码即可。
          </Text>
          <Text>
            2、关于加盟商账户和驿站账户的绑定说明：
            如驿站加盟商账户需绑定同手机号码的快宝驿站账户，请让加盟商自己注册驿站账户后，在这里点击“管理”后重新提交一次加盟商信息即可。
            后续版本会支持自动生成驿站账户并绑定。
          </Text>
        </Row>
      </Drawer>
    </>
  );
};

export default AreamanageDrawer;
